package com.example.lib_cache.view_model;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.lib_cache.dao.UserDao;
import com.example.lib_cache.database.CacheDataBase;
import com.example.lib_cache.model.User;

/**
 * 登录窗体所对应的 ViewModel
 * <p>
 * 处理数据
 * 1.保存到数据库的操作
 * 2.从服务器获取数据
 */
public class LoginActivityViewModel extends ViewModel {
    private static final String TAG = LoginActivityViewModel.class.getSimpleName();
    private MutableLiveData<User> userLiveData;

    public MutableLiveData<User> getUser() {
        if (null == userLiveData) {
            userLiveData = new MutableLiveData<>();
            userLiveData.setValue(new User("778732662@qq.com", "123456", 0, 0));
        }
        return userLiveData;
    }

    public void loginRequest() {
        //请求服务器
//        Log.e(TAG, "User: "+userLiveData.getValue().toString());

        User userBean=new User(
                userLiveData.getValue().getAccount(),
                userLiveData.getValue().getPassWord(),21,1
        );

        //保存到数据库
        //1.获取到数据库的操作引用
        CacheDataBase dataBase=CacheDataBase.getDataBase();
        //2.得到你要操作的表的dao类
        UserDao userDao = dataBase.userDao();
        userDao.insertAll(userBean);

        //更新数据源
        userLiveData.setValue(userBean);
    }

}
